/**
 * 公共请求方封装
 * 以uniapp为例子
 */



// 默认请求配置
const getDefultReqConfig = ()=>({
    url: '',
    method: 'POST',
    header: {
        // ... 默认请求头
    },
    data: {},
    config: {
        loading: false,     // 默认不需要loading加载款
    },
    onSuccess: (data) => data,
    onFail: (err) => err,
    onCompelete: () => { },
})

// 过滤一般请求，这里用code=200代表后端请求正常
const commonResponseFilter = (resultData) => {
    if (resultData.code == 200 || resultData.success == true) {
        return resultData.data;
    }
    // 登录异常
    if(resultData.code==401){
        // @to-do: 跳转登录页
        return false;
    }

    // @to-do: 打印异常信息
    throw new Error(resultData.msg);
}



export default async function request(reqConfig) {
    const req = Object.assign({}, getDefultReqConfig(), reqConfig);
    if (!req.url) {
        return Promise.reject('请求的url不得为空');
    }

    if (req.config?.loading) {
        uni.showLoading({ title: '请求中...' });
    }

    // @to-do: 追加其他信息状态，如Cookie到header中
    req.header = Object.assign({ 
        //...
    }, req.header);

    return new Promise((resolve, reject) => {
        uni.request({
            url: '', //@to-do: 统一处理请求的url
            method: req.method,
            header: req.header, 
            data: req.data,
            success(res) {
                const data = commonResponseFilter(res.data);
                resolve(req.onSuccess? req.onSuccess(data):data);
            },
            fail(err) {
                // @to-do: 打印异常日志
                const reasonError = new Error(`接口${req.url} 异常：`+ err.errMsg);
                reject(req.onFail? req.onFail(reasonError): reasonError);
            },
            complete() {
                req.config?.loading && uni.hideLoading();
                req.onCompelete&&req.onCompelete();
            },
        })
    });
}


